
package cuttings;


import java.io.* ;
import java.net.* ;
import java.util.* ;


final class ReceiveMsg implements Runnable
{
     
     static Socket connectionSocket;
     String hostName;
     String hostIP;
     int port;
     String userName;
     //String myGameHostName = "NULL";

    
    ReceiveMsg(Socket socket)
    {
         connectionSocket = socket;
    }

    public void run()
    {
	try {
	    processRequest();
	} catch (Exception e) {
	    System.out.println(e);
	}
    }

     void processRequest() throws Exception
     {
        try{
        BufferedReader inFromSocket = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream outToSocket = new DataOutputStream(connectionSocket.getOutputStream());
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        InetAddress ClientINet = this.connectionSocket.getInetAddress();
        hostName = ClientINet.getHostName();
        hostIP = ClientINet.getHostAddress();
        port = 0; //how to find port from incoming connection?



        System.out.println("Connection made to "+ hostIP);

        //create a send thread for every incoming socket.
        
        //System.out.println("going to send data");
        //outToSocket.writeBytes("add,"+TCPClient.name+","+TCPClient.hname+","+TCPClient.ip+";");
        //System.out.println("add,"+TCPClient.name+","+TCPClient.hname+","+TCPClient.ip+";");

        System.out.println("waiting to receive peerinfo");
        String peerinfo = inFromSocket.readLine();
        System.out.println("received "+peerinfo);
        PeerInfoList.processPeersInfo(peerinfo,TCPClient.name);
        userName = PeerInfoList.getName(hostIP);
        System.out.println("userName:"+userName);

        SendSockets temp = new SendSockets(hostIP,port,outToSocket,userName);
        SendSocketsList.addSendSocket(temp);

        while(true)
        {
            String sentence = inFromSocket.readLine();
            Menu.updateChatWindow("(" + hostIP + "): " + sentence);
            System.out.println("(" + hostIP + "): " + sentence);

            if(sentence.equalsIgnoreCase("NULL"))
               PeerInfoList.removePeer(hostIP);

            if((sentence.startsWith("interceptedword_"))&&(TCPClient.iAmHost==true))
            {
                //call updateScore and send newscore to successful peer
            }


            //SendSocketsList.sendToAll("#:addAttacker:"+userName);
            if(sentence.startsWith("#"))
            {
                String message[] = sentence.split(":");

                if(message[1].equals("addAttacker"))
                    UserRole.addAttacker(message[2],message[3],Integer.parseInt(message[4]));

                else if(message[1].equals("addDefender"))
                    UserRole.addDefender(message[2],message[3],Integer.parseInt(message[4]));

                if(message[1].equals("removeAttacker"))
                    UserRole.removeAttacker(message[2],message[3],Integer.parseInt(message[4]));

                else if(message[1].equals("removeDefender"))
                    UserRole.removeDefender(message[2],message[3],Integer.parseInt(message[4]));

                else if(message[1].equals("userLogout"))
                {
                    PeerInfoList.removePeer(message[2]);
                    connectionSocket.close();
                }

                else if(message[1].equals("popupInvite"))
                    Menu.popupInvite(userName,message[2]); //userName is name of sender (gamehost)

                else if(message[1].equals("joinedGame"))
                {
                    //joinedGame(who joined)
                    UserRole.joinedGame(message[2]);
                }

                else if(message[1].equals("quitGame"))
                {
                    //quitGame(who quit)
                    UserRole.quitGame(message[2],Integer.parseInt(message[3]));
                }

                else if(message[1].equals("populateParticipants"))
                {
                    String tempNames[] = message[2].split(",");
                    for(int i=0;i<tempNames.length;i++)
                        UserRole.addParticipant(tempNames[i]);
                }

                else if(message[1].equals("populateAttackers"))
                {
                    String tempNames[] = message[2].split(",");
                    for(int i=0;i<tempNames.length;i++)
                        UserRole.addAttackerList(tempNames[i]);
                    UserRole.updateADLists();
                }

                else if(message[1].equals("populateDefenders"))
                {
                    String tempNames[] = message[2].split(",");
                    for(int i=0;i<tempNames.length;i++)
                        UserRole.addDefenderList(tempNames[i]);
                    UserRole.updateADLists();
                }

                else if(message[1].equals("startGameSession"))
                {
                    //call game
                    Player.setToken(ServerConnect.fbToken);
                    Menu.startGame();
                    UserRole.sendOpponentsList(TCPClient.name);
                }

                else if(message[1].equals("attackWithWord"))
                {
                    System.out.println("in attack:"+message[2]+","+message[3]);
                    //display the word in my screen
                    Game.sendAttackWord(message[2],message[3]);
                    Game.displayAttack(message[3],userName);
                }

                else if(message[1].equals("interceptedWord"))
                {
                    //to delete word from display (wordposition,word source username)
                Game.eraseWord(Integer.parseInt(message[2]),message[3]);
                }

                else if(message[1].equals("updateHostScore"))
                {
                    //update score details in host
                    UserRole.updateHostScores(message[2],Integer.parseInt(message[3]),Integer.parseInt(message[4]));
                }

                else if(message[1].equals("updateHostScoreOpponent"))
                {
                    UserRole.updateHostScoreOpponent(message[2],Integer.parseInt(message[3]));
                }

                else if(message[1].equals("updatePeerScore"))
                {
                    //info from host to peer for updating scores
                    UserRole.updatePeerScores(Integer.parseInt(message[2]),Integer.parseInt(message[3]),Integer.parseInt(message[4]));
                }

                else if(message[1].equals("teamChat"))
                {
                    //call function to display teamchat
                    UserRole.showTeamChat(message[2],message[3]);
                }

                else if(message[1].equals("globalChat"))
                {
                    //call function to display teamchat
                    UserRole.showGlobalChat(message[2],message[3]);
                }

                else if(message[1].equals("gameWinLose"))
                {
                    UserRole.gameWinLose(message[2]);
                }

                else if(message[1].equals("file"))
                {
                    receiveFile(Integer.parseInt(message[2]),message[3]);
                    inFromSocket.readLine();
                }
            }

        }
         
     }

     catch(Exception e)
     {

         System.out.println("exception ocurred -" + e.getMessage());
         e.printStackTrace();}
     }


     static public void receiveFile(int filesize, String filename) throws IOException
     {
        //after receiving file send ack
        System.out.println("waiting for file");
        // int filesize=70; // filesize temporary hardcoded

        long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;
        // localhost for testing
        System.out.println("Connecting...");

        // receive file
        byte[] mybytearray = new byte[filesize];
        InputStream is = connectionSocket.getInputStream();
        FileOutputStream fos = new FileOutputStream(filename);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(mybytearray, 0, mybytearray.length);
        current = bytesRead;

        System.out.println("Bytes received:" + mybytearray.length);

        do {
            bytesRead =
                    is.read(mybytearray, current, (mybytearray.length - current));
            System.out.println(bytesRead);
            if (bytesRead > 0) {
                current += bytesRead;
            }
        } while (bytesRead > 0);

        bos.write(mybytearray, 0, current);
        bos.flush();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        bos.close();
        System.out.println(" File received");
        //call vinoth function to q music
    }

}


